<template>
  <div class="loginContainer">
      <img src='/static/images/login_bg@3x.jpg' class='loginBg'/>
      <!-- <div class='login_logo' v-if='userInfo'>
          <image :src="imgHost+userInfo.tenantLogo" class='logo_img'/>
      </div> -->
      <div class='login_logo'>
          <image src="/static/images/logo@3x.png" class='logo_img'/>
      </div>
      <button @getuserinfo="getVxUserInfo" v-if='!authorize' open-type="getUserInfo" class="submit-btn green mt50">微信授权</button>
      <div v-else>
          <!-- 登陆 -->
          <form @submit="loginSubmit" class='login-form' report-submit  v-if='state==1'>
              <div class='submit-wrap'>
                  <div class='input-line mt40'>
                      <div class="col-class">
                            <image src="/static/images/login_icon_user_select@2x.png" class='user_img'/>
                      </div>
                      <div class="col-class input-wrap">
                            <input class='form-input'  type='text' v-model='userName'  placeholder="请输入用户名"/>
                      </div>
                  </div>
                <div class='input-line'>
                    <div class="col-class">
                            <image src="/static/images/login_icon_password_select@2x.png" class='user_img'/>
                      </div>
                      <div class="col-class input-wrap">
                            <input class='form-input pwd' type='password' v-model='password' placeholder="请输入密码"/>
                      </div>
                  </div>
                  <i-row i-class='submit-line'>
                      <button formType="submit" class='submit-btn'>登录</button> 
                  </i-row>
              </div>
          </form> 
          <!-- 绑定 -->
          <form @submit="bindSubmit" class='login-form' report-submit  v-else>
              <div class='submit-wrap'>
                  <div class='input-line mt40' >
                      <div class="col-class">
                            <i-icon type="computer" color="#1380d2" size='24' />
                      </div>
                      <div class="col-class input-wrap">
                            <input class='form-input' type='text' v-model='tenancyId' placeholder="租户编号"/>
                      </div>
                  </div>
                  <div class='input-line'>
                      <div class="col-class">
                            <i-icon type="mine"  size='24' color="#1380d2" />
                      </div>
                      <div class="col-class input-wrap">
                            <input class='form-input' type='text' v-model='wxUserName' placeholder="姓名"/>
                      </div>
                  </div>
                  <div class='input-line'>
                      <div class="col-class">
                            <i-icon type="mobilephone" size='24' color="#1380d2" />
                      </div>
                      <div class="col-class input-wrap">
                            <input class='form-input' v-if='wxTelephone' type='number' v-model='wxTelephone' placeholder="手机号"/>
                            <button v-else @getphonenumber="getPhoneNumber" size='mini' open-type="getPhoneNumber" class="btn-sm green">点击获取</button>
                      </div>
                  </div>
                  <i-row i-class='submit-line'>
                      <button formType="submit" class='submit-btn'>提交申请</button> 
                  </i-row>
              </div>
          </form> 
      </div>
      
      <i-toast id="toast" />
  </div>
</template>

<script type="text/javascript">
import { $Toast } from '@/../static/iview/base/index';
import {mapState,mapActions} from 'vuex';
import moment from 'moment';
const appId="wx4f628833d46a7791"   //开发者appid
const secret="69154bd5ca86df52cc5325c9c504d9f6" 
export default {
  data() {
    return {
        userName:'',
        password:'', 
        isCeng:true,
        userinfo:{}, 
        formid:'',
        urls:[],
        i:0,
        state:'',//0绑定，1登录
        tenancyId:'',//租户id
        wxTelephone:'',
        wxUserName:'',//姓名
      }
  },
  computed:{
    ...mapState(['userInfo','imgHost','authorize','openid','sessionKey']),
  },
  onLoad(){
    this.userName = '';
    this.password = '';
  },
  beforeMount(){
    this.getHostUrls();
    if(this.state){
      wx.setNavigationBarTitle({
        title: '登录' 
      })
    }else{
      wx.setNavigationBarTitle({
        title: '申请绑定' 
      })
    }
  },
  methods:{
    ...mapActions([
        'setImgHost'
    ]),
    loginSubmit(e){
      this.formid = e.mp.detail.formId;
      console.log('this.formid',this.formid)
      let msg='',that = this;
      this.i = 0;
      if(this.userName==''){
        msg = '用户名不能为空'
        this.handleText(msg)
        return;
      }else if(this.password==''){
        msg = '密码不能为空'
        this.handleText(msg)
      }else{
        this.login() 
       // this.pushMsg()//推送消息
      }
    },
    getHostUrls(){
      this.$http.post({
          url:'/hyApi/initServer'
      }).then(res=>{
        if(res.s==0){
          this.urls = res.i.Data;//生产环境
          //this.urls = ['http://192.168.0.154:8081/wo/'];
        }
      }).catch(e=>{
        console.error('获取失败',e)
      })
    },
    login(){
      this.$http.post({
        url:'/common/wxLogin',
        data:{
          host:this.urls[this.i]+'app',
          userName:this.userName,
          password:this.password,
          openId:this.openid
        }
      }).then((res)=>{
        if(res.s==0){
          var msg = '摩派:'+res.m;
          this.handleText(msg)
          this.$store.dispatch('setUserInfo',res.i.Data)
          var reg = /(wo\/)/g;
          var str = this.urls[this.i].replace(reg,'');
          this.setImgHost(str+'repository/');
          this.toIndex();
          this.i = 0
        }else{ 
          this.i++;
          if(this.urls[this.i]) this.login() 
        }
        
      }).catch((e)=>{
        var msg = '摩派:登录失败'
        this.handleText(msg)
      }) 
    },
    pushMsg(){
      /* var data = {
          openid:this.openid,
          formid:this.formid,
          appid:appId,
          appsecret:secret,
          templateid:'TsJ8fqVDbaguQsJMzoULhfXHJB_lUH9ngvo2HPGa1EU',
          keyword1:'10:57',
          keyword2:'17311117916'
      }; */
      var params = ["2019-10-12 15:24","张敏","17310247916"]
      var data = {
        "openid":this.openid,
        "formid":this.formid,
        "appid":appId,
        "appsecret":secret,
        "templateid":"Mad8psA3d3Sl_qWTw5ROwq4toZKwRuzy9uOikK2-eeg",
        "keywords":JSON.stringify(params)
      }
      console.log('data',data)
      this.$http.post({
        url:'/common/pushOneUser',
        data
      }).then((res)=>{
        console.log('推送成功')
      }).catch((e)=>{
        console.log('推送失败',e)
      })
    },
    handleText (msg) {
        $Toast({
            content: msg
        });
    },
    toIndex(){
       wx.switchTab({
        url:'/pages/index/main'
      })
    },
    getUserInfo(data){
      if(data.mp.detail.rawData){
        this.handleUserInfo()
      }
    },
    toDetail(page){
      wx.navigateTo({
        url:`/pages/${page}/main`
      })
    },
    getVxUserInfo(e){			
			if(e.target.userInfo){
        this.isCeng=false;
        this.$store.dispatch('setAuthorize',true)
				this.isLogin()
			}else{
        this.isCeng=true;
        this.$store.dispatch('setAuthorize',false)
			}	
		},		
		isLogin(){		
			var _this=this;
	        wx.getSetting({
	          success(res) {    	          	 
	            if (!res.authSetting['scope.userInfo']) {//未授权getUserInfo            	
	              wx.authorize({
	                scope: 'scope.getUserInfo',
	                success(res) {	                
	                  // 用户已经同意小程序使用用户信息，后续调用 wx.userInfo 接口不会弹窗询问       
                    _this.isCeng=false;
	                  //_this.userName=res.target.userInfo.nickName;
	                  
	                },
	                fail(err){
	                 console.log(err)
	                }
	              })
	            }else{//已授权
	              wx.getUserInfo({
	                success(res) {	
	                	_this.loginOk(res)
	                },
	                fail(err) {
	                  console.log(err)
	                }
	              })
	            }
	          }
	        })
	    },	
		loginOk(res){  //授权成功后的信息处理
      let _this=this;
      _this.isCeng=false;
      wx.setStorageSync('wxAccount', res.userInfo.nickName)
      wx.setStorageSync('gender', res.userInfo.gender)
    },
		getOpenId(){  //获取用户的openid
      let _this=this;
      return new Promise((resolve,reject)=>{
        wx.login({
          success(res) {
                if (res.code) {
                _this.$http.post({
                  url:"/common/getOpenid",
                  data: {
                      host:_this.urls[_this.i]+'app',
                      appid:appId,  //开发者appid
                      secret:secret, //开发者AppSecret(小程序密钥)	
                      js_code: res.code    //wx.login登录获取的code值
                  }
                }).then(res=>{
                if(res.s==0){
                  //_this.openid = res.i.openId;
                  _this.$store.dispatch('setOpenid',res.i.openId)
                  _this.$store.dispatch('setSessionKey',res.i.sessionKey)
                  resolve(res.i.sessionKey)
                }
                }).catch(err=>{
                  console.error('获取失败',err)
                  reject()
                })
              } else {
                console.log('登录失败！' + res.errMsg)
                reject()
              }
          }
        })
      })
    },
    bindSubmit(e){
      /* this.state=1;
      return; */
      this.formid = e.mp.detail.formId;
      if(this.tenancyId==''){
        this.handleText('租户编号不能为空')
        return;
      }else if(this.wxTelephone==''){
        this.handleText('手机号不能为空')
      }else if(this.wxUserName==''){
        this.handleText('姓名不能为空')
      }else{
        this.$http.post({
            url:'/common/insertAppInfor',
            data:{
              host:this.urls[this.i]+'app',
              tenancyId:this.tenancyId,
              wxUserName:this.wxUserName,
              wxTelephone:this.wxTelephone,
              wxAccount:wx.getStorageSync('wxAccount')|| '',
              wxSex:wx.getStorageSync('gender')||'',
              openId:this.openid
            }
        }).then(res=>{
          if(res.s==0 && res.i.Data){
            var reg = /(wo\/)/g;
            var str = this.urls[this.i].replace(reg,'');
            this.setImgHost(str+'repository/');
            this.insertFormId(res.i.sessionId)
            this.getUserState(res.i.sessionId)
            this.i = 0;
            wx.setStorageSync('tenancyId', this.tenancyId)
          }else{
            this.i++;
            if(this.urls[this.i]){
              this.bindSubmit(e)
            }
          }
        }).catch(e=>{
          console.error('获取失败',e)
        })
      }
    },
    getPhoneNumber(e){
      this.getOpenId().then((sessionKey)=>{
        this.$http.post({
          url:'/common/getPhoneNumber',
          data:{
            host:this.urls[this.i]+'app',
            encryptedData:e.mp.detail.encryptedData,
            iv:e.mp.detail.iv,
            'session_key':sessionKey
          }
        }).then(res=>{
          if(res.phoneNumber){
            this.wxTelephone = res.phoneNumber
          }else{
            //this.getPhoneNumber(e)
          }
        }).catch(e=>{
          console.error('获取失败',e)
        })
      })
    },
    insertFormId(sessionId){
      if(this.formid == 'the formId is a mock one') return;
      this.$http.post({
          url:'/common/insertFormId',
          header:{
             'Cookie': wx.getStorageSync('cookieKey'),
             'content-type':'application/x-www-form-urlencoded'
          },
          data:{
            openId:this.openid,
            formId:this.formid,
            formExpiredDate:moment().add(7,'days').format('YYYY-MM-DD HH:mm:ss')
          }
      }).then(res=>{
        console.log('formId保存成功')
      }).catch(e=>{
        console.error('获取失败',e)
      })
    },
     getUserState(sessionId){
      this.$http.post({
          url:'/common/isWxBing',
          header:{
             'Cookie': wx.getStorageSync('cookieKey'),
             'content-type':'application/x-www-form-urlencoded'
          },
          data:{
            openId:this.openid
          }
      }).then(res=>{
        if(res.s==0){
          if(res.i.Data){
            this.i = 0;
            this.state = 1;
            $Toast({
              content:'已绑定成功'
            });
            wx.setStorageSync('userId',res.i.Data)
            wx.switchTab({
              url:`/pages/index/main`
            })
          }else{
            this.state = 0;
            $Toast({
              content:'已申请过，等待绑定'
            });
          }
        }
      }).catch(e=>{
        console.error('获取失败',e)
      })
    }
  }
}
</script>

<style lang='less'>
    page{
        height:100%;
    }
    .loginContainer{
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;
        .loginBg{
          position: absolute;
          left: 0;
          top:0;
          z-index: -1;
          width: 100%;
          height: 100%;
        }
        .login_logo{
          width: 240rpx;
          height: 120rpx;
          margin-top:35%;
          .logo_img{
            width: 100%;
            height: 100%;
          }
        }
        .login-form{
          width:70%;
          margin-top: 50rpx;
          .submit-wrap{
            width:100%;
            .btn-submit{
              background: #1380d2!important;
              font-size:36rpx;
            }
            .input-line{
              display: flex;
              align-items: center;
              border-bottom: 1px solid #2d7eae;
              height: 80rpx;
              &.mt40{
                margin-top: 40rpx;
              }
              .user_img,.pwd_img{
                width: 40rpx;
                height: 40rpx;
                vertical-align: middle;
                margin-top:-6rpx 
              }
              .col-class{
                margin-left:20rpx; 
                &.input-wrap{
                  flex:1
                }
              }
            }
            .submit-line{
              margin-top:50rpx; 
            }
            .form-input{
              width:95%;
              background: transparent;
              color:#1f73ac!important;
              font-size:32rpx;
              margin: 20rpx 0;
              /* &.pwd{
                font-size:26rpx;
              }  */
            }
          }
        }
        .blue{
          color: #1f73ac;
        }
        .w160{
          width: 160rpx;
        }
        .submit-btn{
            width:70%;
            background: #1380d3;
            color:#fff!important;
            font-size:36rpx;
            border-radius:40rpx; 
            height: 80rpx;
            line-height: 80rpx;
            margin-bottom:20rpx;
            &.green{
              background:rgb(26,173,25);
              width:49%;
            }
            &.mt50{
              margin-top:100rpx 
            }
          }
          .btn-sm{
            &:after{
              border:none
            }
            background: none;
            color: #1f73ac;
            font-size:32rpx;
            padding: 0;
            text-decoration: underline;
            height: 56rpx;
          }
    }
</style>
